package readini

import(
	"bufio"
	"io"
	"os"
	"strings"
	"runtime"
	"fmt"
	"reflect"
	"log"
	"time"
)
//注释(window\linux)
var zhushi string
//监听
type Listener interface{
	Listen(infile string)
}
//声明监听函数
type ListenFunc func(string)

func (f ListenFunc) Listen(file string){
	f(file)
}
//初始化
func init(){
	if runtime.GOOS == "windows"{
		zhushi=";"
	}else{
		zhushi="#"
	}
}


// 获取修改时间
func GetFileModTime(path string) int64 {
	f, err := os.Open(path)
	if err != nil {
		log.Println("open file error")
		return time.Now().Unix()
	}

	fi, err := f.Stat()
	if err != nil {
		log.Println("stat fileinfo error")
		return time.Now().Unix()
	}
	f.Close()
	return fi.ModTime().Unix()
}
//Watch函数

/**
 * <api method="Watch" summary="获取目标ini配置文件的配置">
 *     <path path="/github.com/readini">
 *         <query name="filename" type="string" default="" summary="文件名称" />
 *         <query name="run" type="interface{}" default="" summary="监听接口" />
 *     </path>
 *     <tag>user</tag>
 *     <server>users</server>
 *     <response status="200" type="object" mimetype="application/json">
 *         <param name="config" type="map[string]string" summary="目标ini配置文件的配置" />
 *         <param name="error" type="errors"  summary="错误">
 *         </param>
 *         <example mimetype="application/json">
 *         <![CDATA[
 *         {
 *             "config":[
					{"app_mode":"development"}
					{"data":"/home/git/grafana"}
					{"protocol":"http"}
					{"http_port":"9999"}
					{"enforce_domain":true}
 				],
 *             "error": nil
 *         }
 *         ]]>
 *         </example>
 *     </response>
 *     <response status="500" mimetype="application/json" type="object">
 *         <param name="code" type="int" summary="错误代码" />
 *         <param name="msg" type="string" summary="错误内容" />
 *     </response>
 * </api>
 */
func Watch(filenames string, run Listener) (map[string]string,error){
	run.Listen(filenames)
	filename := filenames
	config1 := make(map[string]string)
	f, err :=os.Open(filename)
	if err !=nil{
		panic(err)
	}
	r :=bufio.NewReader(f)
	for{
		b, _, err:=r.ReadLine()
		if err != nil{
			if err == io.EOF{
				break
			}
			panic(err)
		}
		s :=strings.TrimSpace(string(b))
		
		index :=strings.Index(s,"=")
		if index < 0 {
			continue
		}
		key := strings.TrimSpace(s[:index])
		if len(key) == 0{
			continue
		}
		value :=strings.TrimSpace(s[index+1:])
		if len(value) ==0{
			continue;
		}
		config1[key] = value
		fmt.Println(s)
	}
	f.Close()
	return config1,nil
}
//根据Key返回对应Value
func PrintValue(config map[string]string, key string){
	fmt.Println(key,"=",config[key])
}